package com.itheima.service.Impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.ClazzLeaveException;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
@Service
@Transactional
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Override
    public PageBean studentList(StudentQueryParam param) {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<Student> studentList = studentMapper.studentList(param);
        Page<Student> s =(Page<Student>) studentList;
        return new PageBean(s.getTotal(), s.getResult());
    }
    @Override
    public void add(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.add(student);
    }
    @Override
    public Student selectById(Integer id) {
        return studentMapper.selectById(id);
    }
    @Override
    public void update(Student student) {
        List<Student> students = studentMapper.selectAll();
        for (int i = 0; i < students.size(); i++) {
            if (students.get(i).getId().equals(student.getId())) {
                students.remove(students.get(i));
            }
        }
        List<String> idCardList = students.stream().map(Student::getIdCard).toList();
        List<String> noList = students.stream().map(student1 -> student1.getNo()).toList();
        List<String> phoneList = students.stream().map(student1 -> student1.getPhone()).toList();
        if (idCardList.contains(student.getIdCard() ) ){
            throw new ClazzLeaveException("身份证重复");
        }
        if (noList.contains(student.getNo())) {
            throw new ClazzLeaveException("学号重复");
        }
        if (phoneList.contains(student.getPhone())) {
            throw new ClazzLeaveException("手机号重复");
        }
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);
    }

    @Override
    public void delete(List<Integer> ids) {
        studentMapper.delete(ids);
    }
    @Override
    public void deal(Integer id, Integer score) {
        studentMapper.deal(id,score);
    }
}
